package com.googlecode.c4e.ui.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionDelegate;

import com.googlecode.c4e.api.Registry;
import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.ContinuumPlugin;
import com.googlecode.c4e.ui.views.ServersView;

public class DiscardServerAction extends ActionDelegate {

	private Server server;

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection isel = (IStructuredSelection) selection;
			if (isel.getFirstElement() instanceof Server) {
				this.server = (Server) isel.getFirstElement();
			}
		}
	}

	@Override
	public void run(IAction action) {
		if (server != null) {
			try {
				Shell shell = PlatformUI.getWorkbench()
						.getActiveWorkbenchWindow().getShell();
				boolean confirmation = MessageDialog.openQuestion(shell,
						"Discarding server", "Do you want to discard server "
								+ server.getLabel());
				if (confirmation) {
					Registry.getDefault().discardServer(server);
					// TODO find an official way of doing this
					ServersView serversView = (ServersView) PlatformUI
							.getWorkbench().getActiveWorkbenchWindow()
							.getActivePage().findView(
									"com.googlecode.c4e.ui.views.ServersView");
					if (serversView != null) {
						serversView.refreshViewer();
					}
				}
			} catch (Exception e) {
				ContinuumPlugin.getDefault().log("discardServer", e);
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}
}
